#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2011 OpenWrt.org

START=50

USE_PROCD=1
PROG=/usr/sbin/crond

create_rule(){
	config_get user $1 user
	config_get min $1 min "*"
	config_get hour $1 hour "*"
	config_get day $1 day "*"
	config_get month $1 month "*"
	config_get week $1 week "*"
	config_get cmd $1 cmd
	config_get_bool enabled $1 enabled "nil"

	[ "$enabled" = 1 ] && {
		echo  "$min" "$hour" "$day" "$month" "$week" "$cmd"  >> /var/spool/cron/$user
	}
}

get_status(){
	config_get_bool enabled $1 enabled "nil"
	[ "$enabled" != 1 ] && {
		rm -rf /var/spool/cron 2>/dev/null
		echo >&2 "crontab service is disabled"
		exit 1
	}
}

validate_cron_section() {
	uci_validate_section system system "${1}" \
		'cronloglevel:uinteger'
}

start_service () {
#	[ -z "$(ls /etc/crontabs/)" ] && return 1
	loglevel="$(uci_get "system.@system[0].cronloglevel")"

	[ -z "${loglevel}" ] || {
		/sbin/validate_data uinteger "${loglevel}" 2>/dev/null
		[ "$?" -eq 0 ] || {
			echo "validation failed"
			return 1
		}
	}
	mkdir -p /var/spool/cron
	rm -rf /var/spool/cron/* 2>/dev/null
	#ln -s /etc/crontabs /var/spool/cron/ 2>/dev/null
	config_load cron
	config_foreach create_rule rule

	procd_open_instance
	procd_set_param command "$PROG" -f -c /var/spool/cron -l "${loglevel:-5}"
	procd_close_instance
}

service_triggers()
{
	procd_add_validation validate_cron_section
}
